<?php
/***
 * mail
 * class.phpmailer-lite.php
 */
require_once(Q::ini('app_config/MODULE_DIR').'/class.phpmailer.php');
class Helper_Mail extends PHPMailer
{
    /**
     * simple mail 
     */         
    function _ShopMailSend($to,$from,$toname='',$fromname='',$subject='',$body=''){
        $mail->IsSMTP();                           // 启用SMTP 
        $mail->SMTPAuth    = true;                  // 启用SMTP认证 
        
        $mail->SMTPSecure = "ssl";
        $mail->Port        = 465;                    // 端口 
        $mail->Host        = "smtp.qq.com"; // SMTP server 
        $mail->Username    = "5610968@qq.com";     // SMTP server username 
        $mail->Password    = "lxqfuqq250n";            // SMTP server password


// $mail->SMTPSecure = "ssl";
// $mail->Host   = "smtp.gmail.com";
// $mail->Port   = 465;
// $mail->Username  = "lxqunz@gmail.com";
// $mail->Password  = "lxqfugmail250n";
 
      $mail->SetFrom($from, $fromname);
      $mail->AddReplyTo($from,$fromname);

      $mail->AddAddress($to,$toname);

      $mail->Subject   = $subject;   //标题 
      $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test  
      $mail->MsgHTML($body); 
//      $mail->IsHTML(true); // send as HTML 
//       $mail->AddStringAttachment($row["photo"], "YourPhoto.jpg");

        if(!$this->Send()) {
          echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
          echo "Message sent!";
        }
    }
    
	static function send2($myorderid,$mailtemplate_id){
		$O=Myorders::find("[myorderid]=?",$myorderid)->getOne();
		if ($O->isNewRecord()){return false;}
		$M=self::find("[mailtemplate_id]=?",$mailtemplate_id)->getOne();
		if ($M->isNewRecord()){return false;}
		$U=User_Ebay::find("[user_id]=?",$O->uid)->getOne();
		$C=Customers::find("[ecid]=?",$O->ecid)->getOne();
		
		$wuliu=$O->cmorder[0]->detail->country;
		$TrackLink=@Transport::$wuliu_method_TrackLink[$wuliu];
		if (empty($TrackLink)){
			$TrackLink="http://en.4px.cc";
		}

		$title=$M->title;
		$content=$M->content;
		
		//一个订单下面有多个交易,要给每个交易的客人发送邮件
		foreach ($O->transactions as $T){
			//先初始化数组(以防遗漏,替换时发生错误)
			$arrayMail=self::$arrayMail;
			//再覆盖值
			$arrayMail["TransID"]		=$T->transactionid;									//酷贸交易号
			$arrayMail["OrderID"]		=$myorderid;										//酷贸订单号
			$arrayMail["ItemID"]		=$T->itemid;										//Ebay或其他平台的交易号（ItemID），当一个交易号有多个商品时，是数组，自动罗列
			$arrayMail["ItemLink"]		="<a href='http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&Item=".$T->itemid."' target='_balnk'>http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&Item=".$T->itemid."</a>";														//Ebay或其他平台的交易链接，当一个交易号有多个商品时，是数组，自动罗列
			$arrayMail["ItemName"]		=$T->title;											//Ebay或其他平台的交易商品名字，当一个交易号有多个商品时，是数组，自动罗列
			$arrayMail["TrackNumber"]	=$O->shipped_tracking_number;						//商品发送的包裹追踪号码，当一个交易号对应多个包裹号码时，是数组，自动罗列
			$arrayMail["TransDate"]		=date("H:s Y/m/d",$T->created);					//交易生成时间
			$arrayMail["PayDate"]		=date("H:s Y/m/d",$O->paidtime);					//支付完成时间
			$arrayMail["SentDate"]		=date("H:s Y/m/d");									//发货时间
			
			$arrayMail["TrackLink"]		=$TrackLink;										//物流查询网址
			$arrayMail["FEbayName"]		=$U->ebayuserid;									//卖家的ebay帐号
			$arrayMail["MailDate"]		=date("H:s Y/m/d");									//当前发信日期
		 
			$arrayMail["CName"]			=$C->name;											//下单客人的姓名
			$arrayMail["CStreet"]		=$C->street1."<br>".$C->street2;					//下单客人的街道+门牌
			$arrayMail["CPostcode"]		=$C->postalcode;									//下单客人的邮编
			$arrayMail["CCity"]			=$C->cityname;										//下单客人的城市
			$arrayMail["CProvince"]		=$C->stateorprovince;								//下单客人城市所在州
			$arrayMail["CCountry"]		=$C->country;										//下单客人的国家
			$arrayMail["CEmail"]		=$C->email;											//下单客人的邮件地址
			$arrayMail["CEbayname"]		=$O->buyer_id;										//下单客人的ebay名
		 
			$arrayMail["SCName"]		=$O->ship_name;										//收货客人的姓名
			$arrayMail["SCStreet"]		=$O->ship_street1."<br>".$O->ship_street2;			//收货客人的街道+门牌
			$arrayMail["SCPostcode"]	=$O->ship_postalcode;								//收货客人的邮编
			$arrayMail["SCCity"]		=$O->ship_cityname;									//收货客人的城市
			$arrayMail["SCProvince"]	=$O->ship_stateorprovince;							//收货客人城市所在州
			$arrayMail["SCCountry"]		=$O->ship_country;									//收货客人的国家
			$arrayMail["SCEmail"]		=$O->ship_email;									//收货客人的邮件地址
			
			//替换内容
			$title		=htmlspecialchars($M->title);
			$title		=self::replace($title,$arrayMail);
			$content	=$M->content;
			$content	=self::replace($content,$arrayMail);
			$ffrom		=$U->paypal;
			$ffromname	=$U->ebayuserid;
			//$to			=$C->email;
			$to			="guodi.bi@gmail.com";
			//$to			="tkmxxg@163.com";
			$name		=$C->name;
			
			if (empty($ffrom)){
				$ffrom="service@ibay365.com";
			}
			//echo $ffrom."<br>".$ffromname."<br>".$to."<br>".$name."<br>".$title."<br>".$content."<br>";
			//发送邮件
			return self::smtpMail($ffrom,$ffromname,$to,$name,$title,$content,"");
		}
	}
	
	static function smtpMail($ffrom,$ffromname,$to,$name,$title,$content,$attachment=''){
		//SMTP发邮件
		$mail=new Helper_PHPMailer();
        $mail->IsSMTP();                           // 启用SMTP 
        $mail->SMTPAuth    = true;                  // 启用SMTP认证 
        $mail->Port        = 75;                    // 端口 
        $mail->Host        = "mail.coomao.com"; // SMTP server 
        $mail->Username    = "ebay";     // SMTP server username 
        $mail->Password    = "123456abc";           // SMTP server password

        $mail->SetFrom($ffrom, $ffromname);
        $mail->AddReplyTo($ffrom,$ffromname);
        $mail->AddAddress($to,$toname);
  
        $mail->Subject   = $title;   //标题 
        $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test  
        $mail->MsgHTML($content); 
        $mail->AddAttachment($attachment);
		$mail->IsHTML(true);
		if(!$mail->Send()){
			return false;
		}else{
			return true;
		}
	}
	
    static $arrayMail=array(
		"TransID"=>"",		//酷贸交易号
		"OrderID"=>"",		//酷贸订单号
		"ItemID"=>"",		//Ebay或其他平台的交易号（ItemID），当一个交易号有多个商品时，是数组，自动罗列
		"ItemLink"=>"",		//Ebay或其他平台的交易链接，当一个交易号有多个商品时，是数组，自动罗列
		"ItemName"=>"",		//Ebay或其他平台的交易商品名字，当一个交易号有多个商品时，是数组，自动罗列
		"TrackNumber"=>"",	//商品发送的包裹追踪号码，当一个交易号对应多个包裹号码时，是数组，自动罗列
		"TransDate"=>"",	//交易生成时间
		"PayDate"=>"",		//支付完成时间
		"SentDate"=>"",		//发货时间

		"TrackLink"=>"",	//物流查询网址
		"FEbayName"=>"",	//卖家的ebay帐号
		"MailDate"=>"",		//当前发信日期
	 
		"CName"=>"",		//下单客人的姓名
		"CStreet"=>"",		//下单客人的街道+门牌
		"CPostcode"=>"",	//下单客人的邮编
		"CCity"=>"",		//下单客人的城市
		"CProvince"=>"",	//下单客人城市所在州
		"CCountry"=>"",		//下单客人的国家
		"CEmail"=>"",		//下单客人的邮件地址
		"CEbayname"=>"",	//下单客人的ebay名
	 
		"SCName"=>"",		//收货客人的姓名
		"SCStreet"=>"",		//收货客人的街道+门牌
		"SCPostcode"=>"",	//收货客人的邮编
		"SCCity"=>"",		//收货客人的城市
		"SCProvince"=>"",	//收货客人城市所在州
		"SCCountry"=>"",	//收货客人的国家
		"SCEmail"=>"",		//收货客人的邮件地址
    );
    
	static function replace($content,$arrayMail){
		$content=str_replace("&lt;-TransID-&gt;",$arrayMail["TransID"],$content);			//酷贸交易号
		$content=str_replace("&lt;-OrderID-&gt;",$arrayMail["OrderID"],$content);			//酷贸订单号
		$content=str_replace("&lt;-ItemID-&gt;",$arrayMail["ItemID"],$content);				//Ebay或其他平台的交易号（ItemID），当一个交易号有多个商品时，是数组，自动罗列
		$content=str_replace("&lt;-ItemLink-&gt;",$arrayMail["ItemLink"],$content);			//Ebay或其他平台的交易链接，当一个交易号有多个商品时，是数组，自动罗列
		$content=str_replace("&lt;-ItemName-&gt;",$arrayMail["ItemName"],$content);			//Ebay或其他平台的交易商品名字，当一个交易号有多个商品时，是数组，自动罗列
		$content=str_replace("&lt;-TrackNumber-&gt;",$arrayMail["TrackNumber"],$content);	//商品发送的包裹追踪号码，当一个交易号对应多个包裹号码时，是数组，自动罗列
		$content=str_replace("&lt;-TransDate-&gt;",$arrayMail["TransDate"],$content);		//交易生成时间
		$content=str_replace("&lt;-PayDate-&gt;",$arrayMail["PayDate"],$content);			//支付完成时间
		$content=str_replace("&lt;-SentDate-&gt;",$arrayMail["SentDate"],$content);			//发货时间

		$content=str_replace("&lt;-TrackLink-&gt;",$arrayMail["TrackLink"],$content);		//物流查询网址
		$content=str_replace("&lt;-FEbayName-&gt;",$arrayMail["FEbayName"],$content);		//卖家的ebay帐号
		$content=str_replace("&lt;-MailDate-&gt;",$arrayMail["MailDate"],$content);			//当前发信日期
		
		$content=str_replace("&lt;-CName-&gt;",$arrayMail["CName"],$content);				//下单客人的姓名
		$content=str_replace("&lt;-CStreet-&gt;",$arrayMail["CStreet"],$content);			//下单客人的街道+门牌
		$content=str_replace("&lt;-CPostcode-&gt;",$arrayMail["CPostcode"],$content);		//下单客人的邮编
		$content=str_replace("&lt;-CCity-&gt;",$arrayMail["CCity"],$content);				//下单客人的城市
		$content=str_replace("&lt;-CProvince-&gt;",$arrayMail["CProvince"],$content);		//下单客人城市所在州
		$content=str_replace("&lt;-CCountry-&gt;",$arrayMail["CCountry"],$content);			//下单客人的国家
		$content=str_replace("&lt;-CEmail-&gt;",$arrayMail["CEmail"],$content);				//下单客人的邮件地址
		$content=str_replace("&lt;-CEbayname-&gt;",$arrayMail["CEbayname"],$content);		//下单客人的ebay名
	 
		$content=str_replace("&lt;-SCName-&gt;",$arrayMail["SCName"],$content);				//收货客人的姓名
		$content=str_replace("&lt;-SCStreet-&gt;",$arrayMail["SCStreet"],$content);			//收货客人的街道+门牌
		$content=str_replace("&lt;-SCPostcode-&gt;",$arrayMail["SCPostcode"],$content);		//收货客人的邮编
		$content=str_replace("&lt;-SCCity-&gt;",$arrayMail["SCCity"],$content);				//收货客人的城市
		$content=str_replace("&lt;-SCProvince-&gt;",$arrayMail["SCProvince"],$content);		//收货客人城市所在州
		$content=str_replace("&lt;-SCCountry-&gt;",$arrayMail["SCCountry"],$content);		//收货客人的国家
		$content=str_replace("&lt;-SCEmail-&gt;",$arrayMail["SCEmail"],$content);			//收货客人的邮件地址
		
		return $content;
	}
	/***
	 * 客户注册 ,发邮件
	 */
	static public $sendRegister_vars=array(
        'EMAIL_FIRST_NAME'=>'',
        'EMAIL_LAST_NAME'=>'',
        'EMAIL'=>'',
        'CREATED'=>'',
    );
	static function sendRegister($customer){
	    $code='register';
	    if(is_null($customer)||$customer->isNewRecord()) return false;
	    $to=$customer->email;
        $toname=$customer->firstname.' '.$customer->lastname;
        $smt=Store_Mailtemplate::find('store_id=? And code=?',Q::ini('store/store_id'),$code)->getOne();
        if(!$smt->isNewRecord()){
            self::$sendRegister_vars['EMAIL_FIRST_NAME']=$customer->firstname;
            self::$sendRegister_vars['EMAIL_LAST_NAME']=$customer->lastname;
        
            $t=new Helper_Template(self::$sendRegister_vars);
            $title=$t->pauseTemplateZenCartMail($smt->title);
            $content=$t->pauseTemplateZenCartMail($smt->content);
            self::smtpMail(Store::one()->seller_email,Store::one()->seller_name,$to,$toname,$title,$content);
        }
    }
    /***
     * 下订单 
     *     
     */     
    static public $sendOrdercreated_vars=array(
        'username'=>'',
        'email'=>'',
        'created'=>'',
    );    
    static function sendOrdercreated($order){
        return false;
	    $code='ordercreated';
	    $to=$order->ship_email;
        $toname=$order->ship_firstname.' '.$order->ship_lastname;
        $smt=Store_Mailtemplate::find('store_id=? And code=?',Q::ini('store/store_id'),$code)->getOne();
        if(!$smt->isNewRecord()){
            $t=new Helper_Template(self::$sendOrdercreated_vars);
            $title=$t->pauseTemplate($smt->title);
            $content=$t->pauseTemplate($smt->content);
            self::smtpMail(Store::one()->seller_email,Store::one()->seller_name,$to,$toname,$title,$content);
        }
    }
    /***
     * 订单 付款完成  
     *     
     */     
    static public $sendOrderpayed_vars=array(
        'username'=>'',
        'email'=>'',
        'created'=>'',
    );
    static function sendOrderpayed($order){
        return false;
	    $code='orderpayed';
	    $to=$order->ship_email;
        $toname=$order->ship_firstname.' '.$order->ship_lastname;
        $smt=Store_Mailtemplate::find('store_id=? And code=?',Q::ini('store/store_id'),$code)->getOne();
        if(!$smt->isNewRecord()){
            $t=new Helper_Template($sendOrdercreated_vars);
            $title=$t->pauseTemplate($smt->title);
            $content=$t->pauseTemplate($smt->content);
            self::smtpMail(Store::one()->seller_email,Store::one()->seller_name,$to,$toname,$title,$content);
        }
    }
    /***
     *  订单 货发出 
     *     
     */     
    static public $sendOrdershipping_vars=array(
        'username'=>'',
        'email'=>'',
        'created'=>'',
    );
    static function sendOrdershipping($to,$toname,$order){
	    return false;
        $code='ordershipping';
	    
        $smt=Store_Mailtemplate::find('store_id=? And code=?',Q::ini('store/store_id'),$code)->getOne();
        if(!$smt->isNewRecord()){
            $t=new Helper_Template($sendOrdercreated_vars);
            $title=$t->pauseTemplate($smt->title);
            $content=$t->pauseTemplate($smt->content);
            self::smtpMail(Store::one()->seller_email,Store::one()->seller_name,$to,$toname,$title,$content);
        }
    }
    
    static function checkMailtemplate($code){
        $smt=Store_Mailtemplate::find('store_id=? And code=?',Q::ini('store/store_id'),$code)->getOne();
        if(!$smt->isNewRecord()){
            return false;
        }
        return $smt;
    }
    
    /***
     * 添加 邮件 到 db 队列 中 , 等 待 事件 队列 到达后执行 
     */
    static function addQueue ($ffrom,$ffromname,$to,$name,$title,$content,$attachment=''){
        
    }
    /***
     *  执行  邮件  队列 .
     */
    static function sendQueue (){
        
    }
}